package com.itheima.reggie.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.itheima.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {


    @Value("${reggie.path}")//从配置文件application.yml读取普通值(文件将要上传到的目录)
    private String basePath;

    /**
     * 学习实现文件(图片)上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    //MultipartFile对应enctype="multipart/form-data",myFile对应name="myFile
    public R learnUpload(MultipartFile file) {

        System.err.println("原始文件名:" + file.getOriginalFilename());
        System.err.println("原始文件大小:" + file.getSize());

        //获取原始文件名(带后缀的完整名称,不带后缀用myFile.getName())
        String originalFilename = file.getOriginalFilename();//abc.jpg
        //截取出 .后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//.jpg
        //使用UUID(UUID 是 通用唯一识别码（Universally Unique Identifier）的缩写)重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg

//        //创建一个目录对象
//        File dir = new File(basePath);
//        //判断当前目录是否存在
//        if (!dir.exists()) {
//            //目录不存在，需要创建
//            dir.mkdirs();
//        }
//
//        File newFile = new File(basePath, fileName);//创建一个文件对象
//
//        try {
//            file.transferTo(newFile);//将临时文件转存到指定位置
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        System.err.println("新文件名:" + newFile.getName());//file.getName() == fileName
//        System.err.println("新文件大小:" + newFile.length());
//
//
//        return R.success(fileName);//返回新文件名称,为下载做准备



        /**使用OSS对象存储服务替换本地存储文件*/

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-nanjing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tEZYpnKFy3Upv8terdC";
        String accessKeySecret = "gHbDqdUReS1eMclwzoxXKnA6YZgsra";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "bucket-wtp-nj69";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "test/" + fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, objectName, inputStream);//第三个参数是File或者InputStream
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (
                ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return R.success(fileName);//返回新文件名称,为下载做准备*/
    }


    /**
     * 学习实现文件(图片)下载
     * 无返回值,文件不是通过SpringMVC返回的,而是使用原生代码返回的
     *
     * @param name
     */
    @GetMapping("/download")
    public void learnDownload(String name, HttpServletResponse response) throws IOException { //?0b98c285-35c2-463c-a74a-a266227d5229.jpg

//        //确定要下载的文件路径
//        File file = new File(basePath, name);
//        try {
//            //读流
//            FileInputStream fileInputStream = new FileInputStream(file);
//            //写流
//            ServletOutputStream outputStream = response.getOutputStream();//往浏览器输出
////        response.setContentType("image/jpeg");//指定浏览器处理数据的方式,即文件类型,不写也可以
////        int len = 0;
////        byte[] bytes = new byte[1024];//每次读写1个KB
////        while ((len = fileInputStream.read(bytes)) != -1){
////            outputStream.write(bytes,0,len);
////            outputStream.flush();
////        }
//            IOUtils.copy(fileInputStream, outputStream);//使用commons-IO工具包简化IO操作
//
//
//            // 关闭资源
//            fileInputStream.close();
////      无需outputStream.close();因为请求响应结束后请求响应对象就消失了
//
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }


        /**从OSS对象存储服务下载替换从本地文件读取*/

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-nanjing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tEZYpnKFy3Upv8terdC";
        String accessKeySecret = "gHbDqdUReS1eMclwzoxXKnA6YZgsra";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "bucket-wtp-nj69";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "test/" + name;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
            InputStream content = ossObject.getObjectContent();
            if (content != null) {

                //写流
                ServletOutputStream outputStream = response.getOutputStream();//往浏览器输出

                IOUtils.copy(content, outputStream);//使用commons-IO工具包简化IO操作


                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
                content.close();
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
